define([
    "jquery",
    "./lang_en.js","./lang_zh.js"
], function ($,en,zh) {
    // bajaObj：原型，msg：请求获取到的数据，globalColor：全局的颜色，selectOrd：需要默认选中的ord
    // showDate：需要显示的年月，operate：重新请求接口，操作的类型
    var load2 = function (bajaObj,msg,globalColor,selectOrd,showDate,operate) {
        var scheduleType = msg.item.scheduleType;
        if("language" in msg.item){
            if(msg.item["language"]=="zh"){
                var languageData = zh.languageData;
            }else if(msg.item["language"]=="en"){
                var languageData = en.languageData;
            }
        }else{
            var languageData = zh.languageData;
        }
        if(scheduleType == "BooleanSchedule"){
            for(var i=0;i<msg.item.eventOutputs.length;i++){
                if(msg.item.eventOutputs[i]["key"] == "trueText"){
                    msg.item.eventOutputs[i]["key"] = true;
                }else if(msg.item.eventOutputs[i]["key"] == "falseText"){
                    msg.item.eventOutputs[i]["key"] = false;
                }
            }
        }
        if(scheduleType == "EnumSchedule"){
            msg.item.eventOutputs.push({
                key:0,
                value:0
            })
        }



        iconFontAddDisabled();// 让下面所有的按钮都不能点击
        var dayStrArr = languageData.weekArr;
        var monthStrArr = languageData.monthArr;
        // 新建特殊日程
        initDate();
        // 插入各种各样的数据
        function  initDate() {
            var thisYear = new Date().getFullYear();
            var strYear = "<option value='-1'>"+languageData.anyYear+"</option>";
            var notAnyYear = "";
            for(var i=0;i<10;i++){
                var yearNumber = thisYear + i;
                strYear += "<option value='"+yearNumber+"'>"+yearNumber+"</option>";
                notAnyYear += "<option value='"+yearNumber+"'>"+yearNumber+"</option>";
            }
            $(".dateOneYear").empty().append(strYear);
            $(".notAnyYear").empty().append(notAnyYear)
            var strMonth = "<option value='-1'>"+languageData.anyMonth+"</option>";
            var notAnyMonth = "";
            for(var i=0;i<12;i++){
                var monthNumber =  i + 1;
                strMonth += "<option value='"+monthNumber+"'>"+monthStrArr[i]+"</option>";
                notAnyMonth += "<option value='"+monthNumber+"'>"+monthStrArr[i]+"</option>";
            }
            $(".dateOneMonth").empty().append(strMonth);
            $(".notAnyMonth").empty().append(notAnyMonth);
            var strDate = "<option value='-1'>"+languageData.anyDay+"</option>";
            for(var i=0;i<31;i++){
                var dateNumber = i + 1;
                strDate += "<option value='"+dateNumber+"'>"+dateNumber+"</option>";
            }
            $(".dateOneDate").empty().append(strDate);
            var strDay = "<option value='-1'>"+languageData.anyWeek+"</option>";
            for(var i=0;i<7;i++){
                strDay += "<option value='"+i+"'>"+dayStrArr[i]+"</option>";
            }
            $(".dateOneDay").empty().append(strDay);
            if(msg.item.scheduleType!="CalendarSchedule"){
                var typeArr = [{
                    label:languageData.date,
                    value:"Date"
                },{
                    label:languageData.dateRange,
                    value:"DateRange"
                },{
                    label:languageData.reference,
                    value:"Reference"
                }];
            }else{
                var typeArr = [{
                    label:languageData.date,
                    value:"Date"
                },{
                    label:languageData.dateRange,
                    value:"DateRange"
                }];
            }
            
            var typeStr = "";
            for(var i=0;i<typeArr.length;i++){
                var nowData = typeArr[i];
                typeStr += "<option value='"+nowData.value+"'>"+nowData.label+"</option>";
            }
            $('.dataSelect').empty().append(typeStr);
            // 如果是不是特殊日程，则需要显示
            if(msg.item.scheduleType!="CalendarSchedule"){
                var referenceStr = "";
                for(var i=0;i<msg.item.refs.length;i++){
                    var nowData = msg.item.refs[i];
                    referenceStr += "<option value='"+nowData+"'>"+nowData+"</option>";
                }
                $(".referenceSelect").empty().append(referenceStr);
            }
        }

        // 点击新建按钮
        $("#addButton").unbind("click").click(function(e) {
            $("#divmenu").hide();
            var nowTime = new Date();
            // console.log(msg.item.specialPlans.length);
            var newText = languageData.event + (msg.item.specialPlans.length + 1);
            if(defaultDate){
                $(".dataOne .dateOneYear").val(defaultDate.split("-")[0]);
                $(".dataOne .dateOneMonth").val(Number(defaultDate.split("-")[1]));
                $(".dataOne .dateOneDate").val(Number(defaultDate.split("-")[2]));
            }else{
                $(".dataOne .dateOneYear").val(nowTime.getFullYear());
                $(".dataOne .dateOneMonth").val(nowTime.getMonth()+1);
                $(".dataOne .dateOneDate").val(nowTime.getDate());
            }
            
            $(".yearStart").val("-1");
            $(".monthStart").val("-1");
            $(".dateStart").val("-1");
            $(".yearEnd").val("-1");
            $(".monthEnd").val("-1");
            $(".dateEnd").val("-1");

            $(".dateText").val(newText);
            $(".dataTitle").addClass("hide");
            $(".dataName").show();
            $(".dataType").show();
            $(".dateSelectDiv ul").css("margin-top","0px");
            dataSelectChange();
            $(".newEvent").show();
            $(".newEvent").removeClass("dialogHide").addClass("dialogShow");
            // $(".newEvent").slideDown(400);
            e.stopPropagation();
        })
        // 点击关闭按钮
        $(".coloseX").click(function(){
            dialogHide();
        })
        $(".cancelButton").click(function(){
            dialogHide();
        })
        
        function dialogHide(){
            $(".newEvent").removeClass("dialogShow").addClass("dialogHide");
            $(".setDate").removeClass("dialogShow").addClass("dialogHide");;
            $(".deleteDate").removeClass("dialogShow").addClass("dialogHide");;
            $(".renameDate").removeClass("dialogShow").addClass("dialogHide");;
            setTimeout(function(){
                $(".newEvent").hide();
                $(".setDate").hide();
                $(".deleteDate").hide();
                $(".renameDate").hide();
                $(".dialogHide").removeClass("dialogHide");
            },350)
        }


        // 选择不同的类型
        $(".dataSelect").change(function(){
            dataSelectChange();
        })
        function dataSelectChange(){
            var thisValue = $(".dataSelect").val();
            // console.log(thisValue);
            if(thisValue=="Date"){
                $(".dataRang").hide();
                $(".reference").hide();
                $(".dateSelectDiv").height(220);
                $(".dataOne").show();
            }else if(thisValue=="DateRange"){
                $(".reference").hide();
                $(".dataOne").hide();
                $(".dateSelectDiv").height(300);
                $(".dataRang").show();
            }else if(thisValue=="Reference"){
                $(".dataOne").hide();
                $(".dataRang").hide();
                $(".dateSelectDiv").height(220);
                $(".reference").show();
            }
        }

        // 初始化数据
        dataInit(msg.item.specialPlans);// 
        function dataInit(dataArr){
            // console.log(dataArr);
            var str = "";
            for(var i=0;i<dataArr.length;i++){
                var nowData = dataArr[i];
                var dateStr = "";
                if(nowData.specialPlanType=="Date"){
                    dateStr = computerDate(nowData);
                    // console.log(dateStr);
                }else if(nowData.specialPlanType=="DateRange"){
                    dateStr = computerDateRange(nowData);
                    // console.log(dateStr);
                }else if(nowData.specialPlanType=="Reference"){
                    dateStr = computerReference(nowData);
                }
                str += `<dd ord=${nowData.ord} specialPlanType=${nowData.specialPlanType}>
                            <div>
                                <span class="ball"></span>
                                <span>${nowData.text}</span>
                            </div>
                            <p>${dateStr}</p>
                        </dd>`
            }
            $("#specialSchedule .specialList div").empty().append(str);
            letOneSelected(selectOrd);
        }
        // 计算出应该显示的年月日
        function computerDate(nowData){
            var dateStr = "";
            if(nowData.yearStart!="-1"){
                dateStr += nowData.yearStart + languageData.year;
            }
            if(nowData.monthStart!="-1"){
                dateStr += monthStrArr[nowData.monthStart];
            }
            if(nowData.dayStart!="-1"){
                dateStr += nowData.dayStart + languageData.date1 + " ";
            }
            if(nowData.weekdayStart!="-1"){
                dateStr += dayStrArr[nowData.weekdayStart];
            }
            if(dateStr == ""){
                return "*";
            }else{
                return dateStr;
            }
        }
        function computerDateRange(nowData){
            var dateStrStart = "";
            if(nowData.yearStart!="-1"){
                dateStrStart += nowData.yearStart + languageData.year;
            }
            if(nowData.monthStart!="-1"){
                dateStrStart += monthStrArr[nowData.monthStart];
            }
            if(nowData.dayStart!="-1"){
                dateStrStart += nowData.dayStart + languageData.date1;
            }
            if(dateStrStart == ""){
                dateStrStart =  "*";
            }
            var dateStrEnd = "";
            if(nowData.yearEnd!="-1"){
                dateStrEnd += nowData.yearEnd + languageData.year;
            }
            if(nowData.monthEnd!="-1"){
                dateStrEnd += monthStrArr[nowData.monthEnd];
            }
            if(nowData.dayEnd!="-1"){
                dateStrEnd += nowData.dayEnd + languageData.date1;
            }
            if(dateStrEnd == ""){
                dateStrEnd =  "*";
            }
            return dateStrStart + " ~ " + dateStrEnd;
        }
        function computerReference(nowData){
            return nowData.ref;
        }
        // 把选中的时间饿event显示在右侧的时间表中
        function selectEnventOne(ord){
            // console.log(ord);
            if(ord){
                for(var i=0;i<msg.item.specialPlans.length;i++){
                    var nowData = msg.item.specialPlans[i];
                    if(nowData.ord == ord){
                        pullData(nowData);
                    }
                }
            }else{
                // console.log("没有检测到ord，把右侧的事件都清空");
                removeEvent();
            }
        }
        
        function pullData(events){
            // console.log(events,scheduleType);
            if("events" in events && events.events.length!=0){
                var str = "";
                for (var j = 0; j < events.events.length; j++) {
                    var this_data = events.events[j];
                    if (scheduleType == "EnumSchedule") { // 枚举类型
                        var index = 0;
                        // console.log(msg)
                        for (var k = 0; k < msg.item.eventOutputs.length; k++) {
                            if (this_data.effectiveValue == Number(msg.item.eventOutputs[k]["key"])) {
                                index = k;
                            }
                        }
                        var colorItem = globalColor["list"][index%11];
                        var thing = computerThing(this_data['effectiveValue']);
                    } else if (scheduleType == "BooleanSchedule") { //布尔类型
                        var colorItem = globalColor[this_data.effectiveValue];
                        var thing = computerThing(this_data['effectiveValue']);
                    } else if (scheduleType == "StringSchedule") { //字符串类型，数字类型
                        var colorItem = '';
                        var thing = this_data['effectiveValue'];
                    }else if(scheduleType == "NumericSchedule"){ // 数字类型
                        var colorItem = '';
                        if(this_data['effectiveValue']=="null"){
                            var thing = "null";
                        }else{
                            var thing = this_data['effectiveValue'] + " " +msg.item.unit;
                        }
                    }
                    if (this_data.effectiveValue == "null") {
                        var colorItem = "nullitem"
                    }
                    // console.log(colorItem)
                    var finish = this_data['finish'].split(' ')[0] == "00:00" ? "24:00":this_data['finish'].split(' ')[0]
                    str += `<div data-start="${changeTimeToTimestamp(this_data['start'])}" data-end="${changeTimeToTimestamp(this_data['finish'])}" class="event ${colorItem}" style="bottom: ${changTimeToTopAndBottom(this_data['finish'], 'bottom')}; top: ${changTimeToTopAndBottom(this_data['start'], 'top')};">
                                <div class="eventItem" style="cursor: n-resize;">
                                    <span class="thing">${thing}</span><br/>
                                    <span class="start">${this_data['start'].split(' ')[0]}</span>-<span class="end">${finish}</span>
                                </div>
                            </div>`
                }
                $(".root7").append(str);
                $(".root7").removeClass("default");
            }else{
                // console.log("events为空");
                removeEvent();
                $(".root7").removeClass("default");
            }
        }
        // 计算返回的下拉框中的事件
        function  computerThing(params) { // 通过value获取到key
            // console.log(params);
            var thing = "null";
            if(scheduleType == "BooleanSchedule"){
                for(var i=0;i<msg.item.eventOutputs.length;i++){
                    if(params == String(msg.item.eventOutputs[i]["key"])){
                        thing = msg.item.eventOutputs[i]["value"];
                    } 
                }
            }else if(scheduleType== "EnumSchedule"){
                for(var i=0;i<msg.item.eventOutputs.length;i++){
                    if(params == String(msg.item.eventOutputs[i]["key"])){
                        thing = msg.item.eventOutputs[i]["value"];
                    } 
                }
                if(params!="null" && thing=="null"){
                    thing = params;
                }
            }else{
                return params;
            }
            // console.log(thing);
            return thing;
        }
        function  computerThingBack(params) { // 通过key来获取value
            var thing = "null";
            if(scheduleType == "BooleanSchedule" || scheduleType== "EnumSchedule" ){
                for(var i=0;i<msg.item.eventOutputs.length;i++){
                    if(params == String(msg.item.eventOutputs[i]["value"])){
                        thing = String(msg.item.eventOutputs[i]["key"]);
                    } 
                }
            }else{
                return params;
            }
            return thing;
        }
        //根据时间改为时间戳
        function changeTimeToTimestamp(time) {
            var timeCon = time.split(" ")[0];
            var startHour = timeCon.split(":")[0];
            var startMinute = timeCon.split(":")[1];
            var startTime = new Date();
            startTime.setHours(startHour);
            startTime.setMinutes(startMinute);
            startTime.setSeconds(0);
            startTime.setMilliseconds(0);
            // console.log(startTime.getTime())
            return startTime.getTime();
        }
        // 根据时间计算出来top 和 bottom
        function changTimeToTopAndBottom(time, sign) {
            var timeCon = time.split(" ")[0];
            var startHour = Number(timeCon.split(":")[0]);
            var startMinute = Number(timeCon.split(":")[1]);
            // console.log(startHour, startMinute, sign)
            var returnValue = "";
            if (sign == "top") {
                returnValue = (100 * (60 * startHour + startMinute) / 1440).toFixed(4) + '%';
            } else if (sign == "bottom") {
                if (startHour == 0 && startMinute == 0) {
                    startHour = 24;
                }
                returnValue = (100 * (1440 - 60 * startHour - startMinute) / 1440).toFixed(4) + '%';
            }
            // console.log(returnValue);
            return returnValue;
        }

        // 清空右侧的滑块,并设置时间
        function removeEvent(){
            $(".root7").find(".event").remove();
            var thisHour = new Date().getHours() <10 ? "0" + new Date().getHours():new Date().getHours();
            var thisMin = new Date().getMinutes() < 10 ? "0" + new Date().getMinutes():new Date().getMinutes();
            $(".startHour").val(thisHour);
            $(".endHour").val(thisHour);
            $(".startMinute").val(thisMin);
            $(".endMinute").val(thisMin);
            $("#specialSchedule .startHour").attr("disabled",true);
            $("#specialSchedule .endHour").attr("disabled",true);
            $("#specialSchedule .startMinute").attr("disabled",true);
            $("#specialSchedule .endMinute").attr("disabled",true);
            
        }
        // 日程列表选择不同的日程
        $(".specialList dd").unbind("click").click(function(){
            $(".specialList dd").removeClass("selected");
            $(this).addClass('selected');
            var index = $(this).index();
            iconFontAddOrSubDisabled(index);
            var ord = $(this).attr("ord");
            removeEvent();
            selectEnventOne(ord);
            letDateSelected(ord);
        })
        // 日程列表双击
        $(".specialList dd").dblclick(function(){
            $(".specialList dd").removeClass("selected");
            $(this).addClass('selected');
            var index = $(this).index();
            iconFontAddOrSubDisabled(index);
            var ord = $(this).attr("ord");
            removeEvent();
            selectEnventOne(ord);
            letDateSelected(ord);

            var thisValue = $(".specialList .selected").attr("specialPlanType");
            var oldName = $(".specialList .selected").find("span:not('.ball')").text();
            var ord = $(".specialList .selected").attr("ord");
            selectOrd = ord;
            // console.log(ord);
            pullDate(ord);
            $(".dataTitle").text(oldName).removeClass("hide");
            if(thisValue=="Date"){
                $(".dataRang").hide();
                $(".reference").hide();
                $(".dateSelectDiv").height(153);
                $(".dataOne").show();
            }else if(thisValue=="DateRange"){
                $(".reference").hide();
                $(".dataOne").hide();
                $(".dateSelectDiv").height(220);
                $(".dataRang").show();
            }else if(thisValue=="Reference"){
                $(".dataOne").hide();
                $(".dataRang").hide();
                $(".dateSelectDiv").height(153);
                $(".reference").show();
            }
            // 隐藏上面两个li
            $(".dataName").hide();
            $(".dataType").hide();
            $(".dateSelectDiv ul").css("margin-top","15px");
            $(".newEvent").show();
        })
    
        function pullDate(ord){
            for(var i=0;i<msg.item.specialPlans.length;i++){
                var nowData = msg.item.specialPlans[i];
                if(nowData.ord == ord){
                    var thisValue = nowData.specialPlanType;
                    if(thisValue=="Date"){
                        $(".dataOne .dateOneYear").val(nowData.yearStart);
                        if(nowData.monthStart==-1){
                            $(".dataOne .dateOneMonth").val(Number(nowData.monthStart));
                        }else{
                            $(".dataOne .dateOneMonth").val(Number(nowData.monthStart)+1);
                        }
                        $(".dataOne .dateOneDate").val(nowData.dayStart);
                        $(".dataOne .dateOneDay").val(nowData.weekdayStart);
                    }else if(thisValue=="DateRange"){
                        $(".yearStart").val(nowData.yearStart);
                        $(".yearEnd").val(nowData.yearEnd);
                        if(nowData.monthStart==-1){
                            $(".monthStart").val(Number(nowData.monthStart));
                        }else{
                            $(".monthStart").val(Number(nowData.monthStart)+1);
                        }
                        if(nowData.monthEnd==-1){
                            $(".monthEnd").val(Number(nowData.monthEnd));
                        }else{
                            $(".monthEnd").val(Number(nowData.monthEnd)+1);
                        }
                        $(".dateStart").val(nowData.dayStart);
                        $(".dateEnd").val(nowData.dayEnd);
                    }else if (thisValue == "Reference") {
                        $(".referenceSelect").val(nowData.ref);
                    }
                }
            }
        }
        // 根据ord，让某一个选中
        function letOneSelected(ord){
            // console.log(operate)
            if(operate=="add"){
                ord = $(".specialList dd").eq(0).attr("ord");
            }
            // console.log("需要自动选中的ord",ord);
            if(!ord){
                return;
            }
            $(".specialList dd").removeClass("selected");
            var this_ = "";
            for(var i=0;i<$(".specialList dd").length;i++){
                if($(".specialList dd").eq(i).attr("ord")==ord){
                    this_ = $(".specialList dd").eq(i);
                    break;
                }
            }
            if(this_){
                this_.addClass('selected');
                var index = this_.index();
                iconFontAddOrSubDisabled(index);
                removeEvent();
                selectEnventOne(ord);
            }
        }
        // 让按钮显示，能不能点击
        function iconFontAddOrSubDisabled(index){
            // console.log(index);
            $(".toEdit").removeClass("disabled");
            $(".toReanme").removeClass("disabled");
            $(".toDelete").removeClass("disabled");
            var Listlength = $("#specialSchedule .specialList dd").length;
            // 只有一个，都不能使用
            if (Listlength==1){
                $(".toTop").addClass("disabled");
                $(".toBottom").addClass("disabled");
                return;
            }
            if(index==0){ // 如果是第一个，只能向下走
                $(".toTop").addClass("disabled");
                $(".toBottom").removeClass("disabled");
            }else if(index == Listlength-1){ // 如果是最后一个，只能向上
                $(".toTop").removeClass("disabled");
                $(".toBottom").addClass("disabled");
            }else{ // 都不是，上下都可以
                $(".toTop").removeClass("disabled");
                $(".toBottom").removeClass("disabled");
            }
            
        }
        // 让所有的按钮都不能点击
        function iconFontAddDisabled(){
            $(".specialList dd").removeClass("selected");
            removeEvent();
            $(".toEdit").addClass("disabled");
            $(".toReanme").addClass("disabled");
            $(".toDelete").addClass("disabled");
            $(".toTop").addClass("disabled");
            $(".toBottom").addClass("disabled");

        }
        // 选中了，就不自动刷新页面了
        var now = new Date();
        if(selectOrd){
            if(showDate){
                var showYear = showDate.split("/")[0];
                var showMonth = showDate.split("/")[1];
                now.setFullYear(showYear);
                now.setMonth(Number(showMonth)-1);
            }
        }
        CreatNewDate(now.getFullYear(),now.getMonth()+1);
        $(".lastMonth").unbind("click").click(function(e){
            now.setMonth(now.getMonth()-1,1);
            var showMonth = now.getMonth() + 1;
            var showYear = now.getFullYear();
            CreatNewDate(showYear, showMonth);
            e.stopPropagation();
        })
        // 下个月
        $(".nextMonth").unbind("click").click(function(e){
            now.setMonth(now.getMonth()+1,1);
            var showMonth = now.getMonth() + 1 ;
            var showYear = now.getFullYear();
            CreatNewDate(showYear, showMonth);
            e.stopPropagation();
        })
        // 点击日期，显示年月的弹窗
        $(".showDate").unbind("click").click(function(){
            var year = $(this).text().split("/")[0];
            var month = $(this).text().split("/")[1];
            // console.log(year,month);
            $(".dataTitle").addClass("hide");
            $(".notAnyYear").val(year);
            $(".notAnyMonth").val(Number(month));
            $(".setDate .dataOne").show();
            $(".setDate").show();
            $(".setDate").removeClass("dialogHide").addClass("dialogShow")
        })
        $(".setButton").unbind("click").click(function(){
            var year = $(".notAnyYear").val();
            var month = $(".notAnyMonth").val();
            // console.log(year,month);
            now.setFullYear(year);
            now.setMonth(month-1);
            CreatNewDate(year,month);
            $(".setDate").hide();
        })
        // 跳转到今天
        $("#specialSchedule .jumpToday").unbind("click").click(function(e){
            now = new Date();
            var showMonth = now.getMonth() + 1;
            var showYear = now.getFullYear();
            defaultDate = ""; 
            CreatNewDate(showYear, showMonth);
            e.stopPropagation();
        })

        $("#overviewSchedule .jumpToday").click(function(){
            now = new Date();
            var showMonth = now.getMonth() + 1;
            var showYear = now.getFullYear();
            defaultDate = ""; 
            CreatNewDate(showYear, showMonth);
            // e.stopPropagation();
        })

        // 点击一个日期，把这个日期设置为默认日期
        var defaultDate = "";
        $("#specialSchedule .weekContent").on("click",".date",function(){
            var classNameList = $(this).attr("class").split(" ")[0];
            // console.log(classNameList);
            var yearCom = classNameList.slice(4,8);
            var monthCom = classNameList.slice(8,10);
            var dateCom = classNameList.slice(10,12);
            defaultDate = yearCom + "-" + monthCom + "-" + dateCom;
            // console.log(yearCom,monthCom,dateCom,defaultDate);
            $(".weekContent .today").removeClass("today");
            $(this).addClass("today");
        })
        // 点击了一个日期，让其中的日期选中
        function letDateSelected(ord){
            $("#specialSchedule").find(".dateContent .selectedDate").removeClass("selectedDate");
            // console.log(now);
            var year = now.getFullYear();
            var month = now.getMonth() + 1;
            CreatNewDate(year, month)
        }
        // 判断一个年月日，是否符合规则，符合则选中
        function addSelectClass(year,month,date,selectedOrd){  // isOne,表示是不是选中了一个，然后日期只过滤一个
            // console.log(year,month,date,selectedOrd);
            if(selectedOrd){ // 如果有选中的ord，则只需要把对应的ord的日期选中
                for(var i=0;i<msg.item.specialPlans.length;i++){
                    var nowData  = msg.item.specialPlans[i];
                    if(nowData.ord == selectedOrd){
                        if(msg.item.scheduleType!="CalendarSchedule"){
                            if(nowData.events.length!=0){ // 如果没有事件，这个日期是不需要选中的
                                if("calendars" in nowData){ // 如果时引用的类型，则需要往下找一层
                                    for(var j=0;j<nowData.calendars.length;j++){
                                        var nowDataCalendars = nowData.calendars[j];
                                        TypeOfDateAndTypeOfDateRangBefare(year,month,date,nowDataCalendars);
                                    }
                                }else{
                                    TypeOfDateAndTypeOfDateRangBefare(year,month,date,nowData);
                                }
                            }
                        }else{
                            TypeOfDateAndTypeOfDateRangBefare(year,month,date,nowData);
                        }
                    }
                    
                }
            }else{ // 如果没有选中的话，则把原来的全部选中
                for(var i=0;i<msg.item.specialPlans.length;i++){
                    var nowData  = msg.item.specialPlans[i];
                    if(msg.item.scheduleType!="CalendarSchedule"){
                        if(nowData.events.length!=0){ // 如果没有事件，这个日期是不需要选中的
                            if("calendars" in nowData){ // 如果时引用的类型，则需要往下找一层
                                for(var j=0;j<nowData.calendars.length;j++){
                                    var nowDataCalendars = nowData.calendars[j];
                                    TypeOfDateAndTypeOfDateRangBefare(year,month,date,nowDataCalendars);
                                }
                            }else{
                                TypeOfDateAndTypeOfDateRangBefare(year,month,date,nowData);
                            }
                        }
                    }else{
                        TypeOfDateAndTypeOfDateRangBefare(year,month,date,nowData);
                    }
                }
            }
        }
        // 整理数据，然后交给TypeOfDate和TypeOfDateRang处理函数
        function TypeOfDateAndTypeOfDateRangBefare(year,month,date,nowData){
            if(nowData.specialPlanType == "Date"){
                if(TypeOfDate(year,month,date,nowData)){
                    $(".dateContent").find(".date"+year+month+date).addClass("selectedDate")
                }
            }else if(nowData.specialPlanType == "DateRange"){
                if(TypeOfDateRang(year,month,date,nowData)){
                    $(".dateContent").find(".date"+year+month+date).addClass("selectedDate")
                }
            }
        }
        // 判断的是Date类型，是不是满足
        function TypeOfDate(year,month,date,nowData){
            var yearIsOk = false;
            var monthIsOk = false;
            var dateIsOk = false;
            var weekIsOk  = false;
            if(nowData.yearStart!=-1){
                if(year == nowData.yearStart){
                    yearIsOk = true;
                }
            }else{
                yearIsOk = true;
            }
            if(nowData.monthStart!=-1){
                if(Number(month) == Number(nowData.monthStart) + 1){ // 后台保存的是0-11
                    monthIsOk = true;
                }
            }else{
                monthIsOk = true;
            }
            if(nowData.dayStart!=-1){
                if(Number(date) == Number(nowData.dayStart)){
                    dateIsOk = true;
                }
            }else{
                dateIsOk = true;
            }
            if(nowData.weekdayStart!=-1){
                if(new Date(year,Number(month)-1,date).getDay() == nowData.weekdayStart){
                    weekIsOk = true;
                }
            }else{
                weekIsOk = true;
            }
            // console.log( yearIsOk , monthIsOk , dateIsOk , weekIsOk)
            return yearIsOk && monthIsOk && dateIsOk && weekIsOk;
        }
        Date.prototype.Format = function (fmt) { //author: meizz
            var o = {
                "M+": this.getMonth() + 1, //月份
                "d+": this.getDate(), //日
                "H+": this.getHours(), //小时
                "m+": this.getMinutes(), //分
                "s+": this.getSeconds(), //秒
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                "S": this.getMilliseconds() //毫秒
            };
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        }


        // 判断的是Date Rang类型，是不是满足
        function TypeOfDateRang(year,month,date,nowData){
            // console.log(year,month,date,nowData);
            var startTime = new Date();
            var endTime = new Date();
            endTime.setHours(0);
            endTime.setMinutes(0);
            endTime.setSeconds(0);
            endTime.setMilliseconds(0);
            startTime.setHours(0);
            startTime.setMinutes(0);
            startTime.setSeconds(0);
            startTime.setMilliseconds(0);
            if(nowData.yearStart!=-1){ // 不是任意年，则直接赋值原来的nowData中保存的值
                startTime.setFullYear(nowData.yearStart);
            }else { // 任意年，则给赋值我们需要测试的日期的年
                startTime.setFullYear(year);
            }
            if(nowData.monthStart!=-1){ 
                startTime.setMonth(Number(nowData.monthStart),1);
            }else{ 
                startTime.setMonth(Number(month)-1,1);
            }
            if(nowData.dayStart!=-1){
                startTime.setDate(nowData.dayStart);
            }else{
                startTime.setDate(date);
            }
            if(nowData.yearEnd!=-1){
                endTime.setFullYear(nowData.yearEnd);
            }else {
                endTime.setFullYear(Number(year));
            }
            if(nowData.monthEnd!=-1){
                endTime.setMonth(Number(nowData.monthEnd),1);
            }else{
                endTime.setMonth(Number(month)-1,1);
            }
            if(nowData.dayEnd!=-1){
                endTime.setDate(nowData.dayEnd);
            }else{
                endTime.setDate(date);
            }
            
            var thisDateTime = new Date(year,Number(month)-1,date,0,0,0);
            // console.log(nowData)
            // 格式话之后，发现，开始时间大于结束时间 
            if(Number(nowData.dayStart) > Number(nowData.dayEnd) && Number(nowData.monthStart) > Number(nowData.monthEnd)){
                if( thisDateTime.getTime() >=  startTime.getTime() && nowData.yearEnd == -1){
                    endTime.setFullYear(Number(year)+1);
                }
                if(thisDateTime.getTime() <=  endTime.getTime() && nowData.yearStart == -1){
                    startTime.setFullYear(Number(year)-1);
                }
            }else if(nowData.monthStart == -1 && nowData.monthEnd == -1 && Number(nowData.dayStart) > Number(nowData.dayEnd)){
                if(thisDateTime.getTime() < startTime.getTime() && thisDateTime.getTime() > endTime.getTime()){
                    return false;
                }else{
                    if(year>endTime.getFullYear() || year<startTime.getFullYear()){
                        return false;
                    }
                    return true;
                }
            }else if(Number(nowData.monthStart) > Number(nowData.monthEnd)){
                if( Number(month) >=  (Number(nowData.monthStart)+1)){
                    endTime.setFullYear(Number(year)+1);
                }else if(Number(month) <= (Number(nowData.monthEnd)+1)){
                    startTime.setFullYear(Number(year)-1);
                }
            }
            else if(nowData.monthStart == -1 && Number(nowData.dayStart) > Number(nowData.dayEnd)){
                if(thisDateTime.getTime() < startTime.getTime() ){
                    startTime.setMonth(month-2);
                }
                if(thisDateTime.getTime() > endTime.getTime()){
                    endTime.setFullYear(Number(year)+1);
                }
            }
            // XXXX-04-07 - XXXX-04-02
            else if(nowData.monthStart == nowData.monthEnd && Number(nowData.dayStart) > Number(nowData.dayEnd)){
                if(thisDateTime.getTime() < startTime.getTime() && thisDateTime.getTime() > endTime.getTime()){
                    return false;
                }else{
                    return true;
                }
            }
            
            // 单独的一种情况，解释不太清楚  2021-04-XX - XXXX-06-XX
            if(nowData.yearStart!=-1 && nowData.yearEnd == -1){
                if(nowData.monthStart < nowData.monthEnd){
                    if(year>=nowData.yearStart ){
                        return true;
                    }
                }else{
                    if(year < nowData.yearStart){
                        return false;
                    }
                    if(thisDateTime.getTime() < startTime.getTime() && thisDateTime.getTime() > endTime.getTime()){
                        return false;
                    }else{
                        return true;
                    }
                }
            }
            
            if(nowData.yearStart==-1&&nowData.yearEnd!=-1){
                if(year < nowData.yearEnd && nowData.monthStart > nowData.monthEnd){
                    return true;
                }
            }

            // console.log(startTime.Format("yyyy-MM-dd"),endTime.Format("yyyy-MM-dd"),thisDateTime.Format("yyyy-MM-dd"));
            // console.log(startTime.getTime(),endTime.getTime(),thisDateTime.getTime());
            if(thisDateTime.getTime() >= startTime.getTime() && thisDateTime.getTime() <= endTime.getTime()){
                return true;
            }else{
                return false;
            }
        }

        // 时间表函数
        // 创建有个新的时间日历
        function CreatNewDate(year, month) { // month的范围时1-12
            if (month < 10) {
                month = "0" + month
            }
            $('.showDate').text(year + "/" + month);
            var lastDate = getMonthLastDateFn(year, month);
            var weekNumber = getWeek(year, month, 1);
            // console.log(year,month," 最后的一个月的结束日：",lastDate," 第一天时周几：" ,weekNumber);
            var week0 = "";
            var week1 = "";
            var week2 = "";
            var week3 = "";
            var week4 = "";
            var week5 = "";
            var week6 = "";

            for (var i = 0; i < 42; i++) {
                var dateNumber = i - weekNumber + 1; //得到现在是几号，一号之前的，都是小于等于0的
                var weekNo = parseInt(i / 7); // 得到的现在是第几周
                if (dateNumber >= 1 && dateNumber <= lastDate) {
                    if (dateNumber < 10) {
                        dateNumber = "0" + dateNumber
                    }
                    var className = 'date' + year + month + dateNumber + ' day' + (i) % 7 + ' date';
                    // console.log(className)
                    if (weekNo == 0) {
                        week0 += "<p class='" + className + "'>" + '<span>' +dateNumber + '</span>' +"</p>";
                    } else if (weekNo == 1) {
                        week1 += "<p class='" + className + "'>" + '<span>' +dateNumber + '</span>' + "</p>";
                    } else if (weekNo == 2) {
                        week2 += "<p class='" + className + "'>" + '<span>' +dateNumber + '</span>' + "</p>";
                    } else if (weekNo == 3) {
                        week3 += "<p class='" + className + "'>" + '<span>' +dateNumber + '</span>' + "</p>";
                    } else if (weekNo == 4) {
                        week4 += "<p class='" + className + "'>" + '<span>' +dateNumber + '</span>' + "</p>";
                    } else if (weekNo == 5) {
                        week5 += "<p class='" + className + "'>" + '<span>' +dateNumber + '</span>' + "</p>";
                    }

                } else if (dateNumber < 1) {
                    week0 += "<p class='empty'></p>";
                } else if (dateNumber > lastDate) {
                    if (weekNo == 4) {
                        week4 += "<p class='empty'></p>";
                    } else if (weekNo == 5) {
                        week5 += "<p class='empty'></p>";
                    }
                }
            }
            $(".week0").empty().append(week0);
            $(".week1").empty().append(week1);
            $(".week2").empty().append(week2);
            $(".week3").empty().append(week3);
            $(".week4").empty().append(week4);
            $(".week5").empty().append(week5);
            todaySel();

            if($("#scheduleHeader .sel").index()==2){ // 当是日程总览的时候，选中
                getWeekData();
            }
            var selectedOrd = "";
            selectOrd = $("#specialSchedule .specialList .selected").attr("ord");
            for(var i=1;i<lastDate+1;i++){
                var Date = i<10 ? "0" + i:i;
                addSelectClass(year,month,Date,selectOrd);
            }
        }

        function getWeekData(){
            bajaObj.ajax({
                item: {
                    background: null,
                    scheduleOrd: msg.item.scheduleOrd,
                    type: "readWeeklySchedule"
                },
                showType: "RefreshWeekly"
            }, weekajaxSuccess, weekajaxError);
        }
        function weekajaxSuccess(msg){
            msg.item.weekPlans.map((item,i)=>{
                if(item.events.length!=0){
                    setDaySelect(i);
                }
            })
        }
        function weekajaxError(){};
        // 让一个与的周几全部选中
        function setDaySelect(day) {
            if (day == 7) {
                day = 0;
            }
            $(".dateContent").find(".day" + day).addClass("selectedDate");
        }
        // 选中今天
        function todaySel(){
            if(defaultDate){
                var year = defaultDate.split("-")[0];
                var month = defaultDate.split("-")[1];
                var date = defaultDate.split("-")[2];
            }else{
                var nowDate = new Date();
                var year = nowDate.getFullYear();
                var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
                var date = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
            }
            $(".dateContent").find(".date"+year+month+date).addClass("today");
            
            
        }
        // 获取一个月的最后一天
        function getMonthLastDateFn(year, month) {
            var dateObj = new Date(year, month, 0);  //注意：这里传入月份取值范围是1-12
            var theMonthDay = dateObj.getDate();
            return theMonthDay;
        }
        // 获取一个日期是周几
        function getWeek(year, month, date) {
            month--;
            return new Date(year, month, date).getDay();
        }
        // 点击其他地方，隐藏选中
        $("#specialLeft:not('.dateContent')").unbind("click").click(function(){
            // console.log("点击了其他的地方");
            // selectOrd = "";
            iconFontAddDisabled();
            CreatNewDate(now.getFullYear(),now.getMonth()+1);

        })
        $("#specialLeft:not('.addButton')").unbind("click").click(function(){
            // console.log("点击了其他的地方");
            // selectOrd = "";
            iconFontAddDisabled();
            CreatNewDate(now.getFullYear(),now.getMonth()+1);
        })

        document.getElementById("scheduleRootOther").oncontextmenu = function (e) {
            $("#copyLi").hide();
            $("#psateLi").hide();
            $("#removeWeekLi").hide();
            $("#copyMToFLi").hide();
            $("#defaultLi").show();
            $("#divmenu").height(115);
            var menuWidth = $("#divmenu").width();
            var menuHeight = $("#divmenu").height();
            var parentDivLeft = $("#scheduleRootOther").offset().left;
            var parentDivTop = $("#scheduleRootOther").offset().top;
            var parentWidth = $("#schedule").width();
            var timeWidth = $("#scheduleRootOther").width();
            var leftValue = e.clientX - parentDivLeft + parentWidth - timeWidth;
            var topValue = e.clientY - parentDivTop + 56;
            if(leftValue > parentWidth - menuWidth){
                leftValue = leftValue - menuWidth;
            }
            $("#divmenu").css({ "left": leftValue + "px", "top": topValue + "px", "display": "block" });
            return false;
        }
    }
    return {
        load2: load2
    }

});

